package org.tony.spider.common.cmd;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.tony.spider.common.Command;
import org.tony.spider.common.Rule;
import org.tony.spider.util.SpiderConfigParser;

public class CommandInvoker
{
  Map<CmdType, Invoker>         invokers = null;

  private static CommandInvoker instance = new CommandInvoker();

  public CommandInvoker()
  {
    invokers = new HashMap<CmdType, Invoker>();
    try
    {
      invokers.put(CmdType.fetch, new FetchCommandInvoker());
      invokers.put(CmdType.remove, new RemoveCommandInvoker());
    }
    catch (Exception e)
    {
    }
  }

  public static CommandInvoker getInstance()
  {
    return instance;
  }

  public Object invoke(Command cmd, Object target)
  {
    try
    {
      return invokers.get(cmd.getType()).invoke(cmd, target);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

  public static void main(String[] args)
  {
    String xml = "<html><div>aaaaaaaaaaaaaa<p>dsadasdsa</p><a href='aa'>ssss</a></div><div>aaaaaaaaaaaaaa<p>dsadasdsa</p><a href='aa'>ssss</a></div></html>";
    Document doc = Jsoup.parse(xml);
    Elements elements = null;
    Object arg = doc;
    Rule rule = SpiderConfigParser.getInstance().getNovelRule("demo");
    if (rule != null)
    {
      Iterator<Command> iter = rule.getCommands().iterator();
      while (iter.hasNext())
      {
        elements = (Elements)CommandInvoker.getInstance().invoke(iter.next(), arg);
        arg = elements;
      }
    }
    System.out.println(elements);
  }
}
